package com.songshan.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.songshan.bean.Menu;
import com.songshan.bean.User;
import com.songshan.dao.MenuMapper;
import com.songshan.dto.Result;
import com.songshan.filter.UserContext;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author feb
 * @date 2024/6/18
 * @Description: 权限校验拦截器
 */
@Component
public class PermissionsInterceptor implements HandlerInterceptor {

  @Autowired
  private MenuMapper menuMapper;

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {
    User user = UserContext.get();
    if(user==null){
      Result result = new Result();
      result.setCode(403);
      result.setMsg("登录过期！");
      response.setCharacterEncoding("utf-8");
      response.setContentType("application/json");
      PrintWriter out = response.getWriter();
      out.println(JSONObject.toJSONString(result));
      out.flush();
      out.close();
      return false;
    }
    if (user.getUsername().equals("admin")) {
      return true;
    }
    String uri = request.getRequestURI();
    List<Menu> list = menuMapper.selectMenuByUser(user.getId());
    long cnt = list==null?0l:list.stream()
        .filter(menu -> menu.getUri()!=null && menu.getUri().contains(uri))
        .count();
    if (cnt==0l) {
      Result result = new Result();
      result.setCode(503);
      result.setMsg("权限不足：" + uri);
      response.setCharacterEncoding("utf-8");
      response.setContentType("application/json");
      PrintWriter out = response.getWriter();
      out.println(JSONObject.toJSONString(result));
      out.flush();
      out.close();
      return false;
    }
    return true;
  }
}
